package config

import (
	"errors"
	"fmt"
	"gopkg.in/yaml.v3"
	"io/ioutil"
)

const CfgPath = "/home/zf/data/zf/code/src/asystem/pays/config/pay.yaml"

type ReadCfg struct{}

type AlipayCfg struct {
	AliAppid                string `json:"appid"`
	AliPrivate              string `json:"privatekey"`
	AliAppCertPublicKeyFile string `json:"aliappcertpublickeyfile"`
	AliPayRootCert          string `json:"alipayrootcert"`
	AliPayCertPublicKeyRSA2 string `json:"alipaycertpublickeyrsa2"`
	AliNotifyUrl            string `json:"alinotifyurl"`
	AliReturnUrl            string `json:"alireturnurl"`
	AliSubject              string `json:"alisubject"`
	AliIsProduction         bool   `json:"isproduction"`
}

type WxPayCfg struct {
}

type PayCfg struct {
	WxPay  *WxPayCfg  `json:"wxpay"`
	Alipay *AlipayCfg `json:"alipay"`
}

func NewReadCfg() *ReadCfg {
	return &ReadCfg{}
}

func (r *ReadCfg) OpenCfgFile(path string) (yamlFile []byte, err error) {
	if yamlFile, err = ioutil.ReadFile(path); err != nil {
		err = errors.New(fmt.Sprintf("打开配置文件出错，请检查配置文件的路径是否正确，错误代码：%v", err))
		return
	}
	return
}

func (r *ReadCfg) ParseYaml(yamlFile []byte) (*PayCfg, error) {
	yamlObj := new(PayCfg)
	if err := yaml.Unmarshal(yamlFile, yamlObj); err != nil {
		return nil, errors.New(fmt.Sprintf("解析配置文件出错，错误代码：%v", err))
	}
	return yamlObj, nil
}

// LoadCfg 读取配置文件
func (r *ReadCfg) LoadCfg(path string) (*PayCfg, error) {
	cfgObj := NewReadCfg()
	file, err := cfgObj.OpenCfgFile(path)
	if err != nil {
		return nil, err
	}
	yamlObj, err := cfgObj.ParseYaml(file)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	return yamlObj, nil
}
